package com.itbaizhan.shopping_manager_api.controller;

import com.itbaizhan.shopping_common.result.BaseResult;
import com.itbaizhan.shopping_common.service.FileService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author spf
 * @date 2023/12/23
 * @time 11:18
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Reference
    private FileService fileService;

    /**
     * 上传图片文件
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadImage")
    public BaseResult<String> uploadImage(MultipartFile file) throws IOException {
        // MultipartFile对象不能再服务间传递，必须转为byte数组
        byte[] fileBytes = file.getBytes();
        String filename = file.getOriginalFilename();
        String imageUrl = fileService.uploadImage(fileBytes, filename);
        return BaseResult.ok(imageUrl);
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     * @return 执行结果
     */
    @DeleteMapping("/delete")
    public BaseResult delete(String filePath){
        fileService.delete(filePath);
        return BaseResult.ok();
    }

}
